package com.data.action

import com.data.annotation.NoargAnnotation
import com.data.annotation.OpenAnnotation
import com.data.bean.Account
import com.data.service.LoginService
import com.data.util.FinalStringUtils
import com.data.util.VerificationCodeUtil
import org.apache.log4j.Logger
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import java.awt.image.BufferedImage
import java.io.ByteArrayOutputStream
import java.io.IOException
import javax.imageio.ImageIO
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse


@Controller
@OpenAnnotation
@NoargAnnotation
class LoginAction {


    @Autowired
    private var loginService: LoginService? = null

    @RequestMapping("login")
    fun loginInputAction(request: HttpServletRequest): String {
        val cookies = request.cookies
        if (cookies != null) {

            for (c in cookies) {
                if (c.name == "username") {
                    request.setAttribute("username", c.value)
                } else if (c.name == "password") {
                    request.setAttribute("password", c.value)
                }
            }

        }

        return "login"
    }


    /**
     * 验证码校验方式
     *
     * @param ucode
     * @param request
     * @return
     */
    private fun authCodeCheckAction(ucode: String, request: HttpServletRequest): Boolean {
        //判断这个authcode是否是null
        request.session.getAttribute("authcode") ?: return false
        val authcode: String = request.session.getAttribute("authcode") as String
        // 如果验证码是空，就赋值为空格
        return authcode.toLowerCase() == ucode.trim().toLowerCase()
    }


    /**
     * 将图片转化为字节流
     *
     * @param image
     * @return
     */
    private fun convertImageToStream(image: BufferedImage): ByteArray {
        val out = ByteArrayOutputStream()
        try {
            ImageIO.write(image, "jpeg", out)// 将图片流写入发哦输出流中
        } catch (e: IOException) {

            e.printStackTrace()
        }
        return out.toByteArray()
    }

    /**
     * 请求验证码
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @GetMapping(value = "/authcode")
    @Throws(IOException::class)
    fun getAuthCodeAction(request: HttpServletRequest, response: HttpServletResponse) {
        val authcode = VerificationCodeUtil.authCode//获取验证码
        request.session.setAttribute("authcode", authcode)//添加验证码到session中
        val authImage = VerificationCodeUtil.getAuthImage(authcode)
        val inputStream = convertImageToStream(authImage)
        response.contentType = "image/png"
        val stream = response.outputStream
        stream.write(inputStream)
        stream.flush()
        stream.close()
    }

    /**
     * 登录账号，传入用户名，密码，验证码三个参数
     */
    @PostMapping("submitLogin")
    fun loinAction(username: String, password: String, ucode: String, request: HttpServletRequest): String {
        var ERROR = "验证码错误"
        if (authCodeCheckAction(ucode, request)) {
            //安全的空调用
            val account = loginService?.loginService(username, password)
            ERROR = if (account != null) {
                request.session.setAttribute(FinalStringUtils.ACCOUNT, account)
                when (account.types) {
                //如果身份正确就直接调用LoginIndex()，然后自动定位到相应的界面
                    FinalStringUtils.ADMIN, FinalStringUtils.USER -> return loginIndex(request)
                    else -> "登录出错"
                }

            } else
                "账号或者密码错误"
        }
        request.setAttribute("username", username)
        request.setAttribute("error", ERROR)
        return "login"
    }

    @GetMapping("index")
    fun loginIndex(request: HttpServletRequest): String {
        val account = request.session.getAttribute(FinalStringUtils.ACCOUNT) as Account
        return when {
            account.types == FinalStringUtils.ADMIN -> "redirect:/adminIndex/admin/index"
            account.types == FinalStringUtils.USER -> "redirect:/adminIndex/user/index"
            else -> "login"
        }


    }
}

